# Create your views here.
import json

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.contrib.auth.hashers import check_password
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from apps.cart.utils import merge_cart_cookie_to_redis
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User
from meiduo_market import settings

# qq/authorization/?next=/
"""
点击QQ登录图标  进入第三方登录页面
"""


class QQLoginView(View):
    def get(self, request):
        # 创建OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state='xxx')
        # OAuthQQ对象.get_qq_url()方法来获取第三方登录页面
        login_url = oauth.get_qq_url()

        # 返回这个页面的url
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': login_url})


# /oauth_callback/?code=8E36ED6C3ADB0E51BED5CF605268E189
"""
QQ登录授权后的回调函数
"""


class OauthView(View):
    def get(self, request):
        # 获取QQ登录授权后返回的code
        code = request.GET.get('code')
        # 创建OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state='xxx')
        # OAuthQQ对象.get_access_token(code)来获取access_token
        access_token = oauth.get_access_token(code)
        # OAuthQQ对象.get_open_id(access_token)来获取这个QQ用户的openid
        open_id = oauth.get_open_id(access_token)

        # 根据openid去数据库查询这个qq号是否存在与手机号绑定
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=open_id)
        except Exception as e:
            # 查不到捕获异常
            print(e)
            # 把open_id加密
            open_id = generate_access_token(open_id)
            # 传给前端的绑定页面，去和手机号绑定
            return JsonResponse({'code': 400, 'errmsg': '未绑定', 'access_token': open_id})
        # 如果这个QQ号与某个用户的手机号绑定过了就直接登录  状态保持  添加cookie
        else:
            login(request, oauth_qq_user.user)

            ret = JsonResponse({'code': 0, 'errmsg': 'ok'})
            ret.set_cookie('username', oauth_qq_user.user.username, max_age=3600 * 24 * 5)
            response = merge_cart_cookie_to_redis(request, request.user, ret)
            return response

    # 绑定页面逻辑
    def post(self, request):
        # 获取用户输入的数据
        data_dict = json.loads(request.body)

        # 密码  手机号  短信验证码 和  传过来的openid
        password = data_dict.get('password')
        mobile = data_dict.get('mobile')
        sms_code = data_dict.get('sms_code')
        open_id = data_dict.get('access_token')

        # 校验参数
        if not all([password, mobile, sms_code, open_id]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})

        # 解密openid
        open_id = check_access_token(open_id)

        # 取出redis内的短信验证码校验
        redis_cli = get_redis_connection('code')
        redis_sms_code = redis_cli.get('sms_%s' % mobile)
        if not redis_sms_code:
            return JsonResponse({"code": "400", "errmsg": "短信验证码已过期"})
        if sms_code != redis_sms_code.decode():
            return JsonResponse({"code": "400", "errmsg": "短信验证码不正确"})

        # 查询当前手机号是否注册过了
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 没有查询到就说明没有注册过，注册一个
            print(e)
            user = User.objects.create_user(mobile=mobile, username=mobile, password=password)
        else:
            # 注册过直接验证密码对不对  如果对就绑定当前用户和QQ号  添加到数据库
            if not check_password(password, user.password):
                return JsonResponse({"code": "400", "errmsg": "您输入的手机号已经注册过，但是密码输入不正确"})

        try:
            OAuthQQUser.objects.create(
                user=user,
                openid=open_id
            )
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "该手机号已经绑定了QQ，请重新输入"})
        else:
            login(request, user)
            ret = JsonResponse({'code': 0, 'errmsg': 'ok'})
            ret.set_cookie('username', user.username, max_age=3600 * 24 * 5)
            response = merge_cart_cookie_to_redis(request, user, ret)
            return response
